package com.viewpagertext.fragments;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.viewpagertext.DBHelper.AppDatabase;
import com.viewpagertext.DBHelper.Dao.UserDao;
import com.viewpagertext.Model.User;
import com.viewpagertext.R;

import static com.viewpagertext.activitys.MainActivity.Username;



public class LoginFragment extends Fragment {


    private TextView userRegisterBtn;
    private TextView loginBtn;
    private EditText passwordEdit;
    private EditText usernameEdit;
    UserDao helper = AppDatabase.getInstance().UserDao();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_login, null);
//        initView();
        loginBtn = v.findViewById(R.id.loginBtn);
        usernameEdit = v.findViewById(R.id.usernameEdit);
        passwordEdit = v.findViewById(R.id.passwordEdit);
        userRegisterBtn = v.findViewById(R.id.userRegisterBtn);
        userRegisterBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager fm = getActivity().getSupportFragmentManager();
                fm.beginTransaction()
                        //替换为RegisterFragment
                        .replace(R.id.frameContain, new RegisterFragment())

                        .commit();
            }
        });
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = String.valueOf(passwordEdit.getText());
                String username = String.valueOf(usernameEdit.getText());
                if (password.equals("") || username.equals(""))
                    Toast.makeText(getActivity(), "账号或密码不为空", Toast.LENGTH_SHORT).show();
                else if (helper.getUser(username, password) != null) {
                    Username = username;
                    Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "账号或密码错误", Toast.LENGTH_SHORT).show();
                }
            }

            //进行注册功能

        });
        return v;
    }
}
